package xl.service;


import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

// DeepSeekService.java
@Service
public class DeepSeekService {
    private static final String API_URL = "https://openapi.coreshub.cn/v1/chat/completions";
    private final OkHttpClient client = new OkHttpClient();

    private String apiKey="sk-XB5Bxk5CWZLHTguXsH4q72MT4YULhKQGewgRVrKejOvyxx4O";
    private String embeddingUrl="https://openapi.coreshub.cn/v1/embeddings";
    private String embeddingModel="bge-m3";
    private String chatModel="DeepSeek-V3";

    // 生成文本
    public String generateText(String prompt) throws IOException {
        JSONObject body = new JSONObject();
        body.put("model", chatModel);
        body.put("messages", new JSONArray()
                .put(new JSONObject()
                        .put("role", "user")
                        .put("content", prompt)));
        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(body.toString(), MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        try (Response response = client.newCall(request).execute()) {
            JSONObject responseBody = new JSONObject(response.body().string());
            return responseBody.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
        }

    }

    // 获取文本嵌入
    public List<Double> getEmbedding(String text) throws IOException {
        // 假设DeepSeek提供embedding接口（需根据实际API调整）
        JSONObject body = new JSONObject();
        body.put("input", text);
        body.put("model", embeddingModel);

        Request request = new Request.Builder()
                .url(embeddingUrl)
                .post(RequestBody.create(body.toString(), MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        try (Response response = client.newCall(request).execute()) {
            // 检查HTTP响应状态码
            if (!response.isSuccessful()) {
                String errorBody = response.body() != null ? response.body().string() : "empty body";
                throw new IOException("HTTP请求失败，状态码: " + response.code() + "，响应体: " + errorBody);
            }

            // 确保响应体不为空
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                throw new IOException("响应体为空");
            }

            JSONObject jsonResponse = new JSONObject(responseBody.string());

            // 安全获取嵌套字段
            JSONArray dataArray = jsonResponse.optJSONArray("data");
            if (dataArray == null) {
                throw new RuntimeException("响应中缺少 'data' 字段或数组为空");
            }

            JSONObject firstData = dataArray.optJSONObject(0);
            if (firstData == null) {
                throw new RuntimeException("data数组第一个元素不是JSON对象");
            }

            JSONArray embeddingArray = firstData.optJSONArray("embedding");
            if (embeddingArray == null) {
                throw new RuntimeException("缺少 'embedding' 字段");
            }

            // 转换到Double列表，处理格式错误
            return embeddingArray.toList().stream()
                    .map(obj -> {
                        try {
                            return Double.valueOf(obj.toString());
                        } catch (NumberFormatException e) {
                            throw new RuntimeException("无法转换到Double: " + obj, e);
                        }
                    })
                    .collect(Collectors.toList());

        } catch (IOException e) {
            throw new RuntimeException("网络请求异常: " + e.getMessage(), e);
        } catch (JSONException e) {
            throw new RuntimeException("JSON解析异常: " + e.getMessage(), e);
        }
    }
}

